"use strict";

// 数组遍历
function arrayLoop() {
    let month = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];

    console.log("type of month : " +typeof(month));

    for (var index = 0; index < month.length; index += 1) {
        console.log("for loop : " + index + ", " + month[index]);
    }

    month.forEach((element, index) => {
        console.log("for each : " + index + ", " + element);
    })

    let loop = 0;
    for (var str of month) {
        console.log("for of : " + loop + ", " + str);
        loop += 1;
    }

    // 对象使用 for in 循环取所有的键值对
    for (var key in month) {
        console.log("for in : " + key + ", " + month[key]);
    }
}

// 数组深拷贝
function deepClone(obj) {
    var newObj = obj instanceof Array ? [] : {}
    for (var i in obj) {
        newObj[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]

    }
    return newObj
}

// 数组排序
function arraySort() {
    let month = [
        "January",
        "February",
        "March",
        "April",
        "May",
        "June",
        "July",
        "August",
        "September",
        "October",
        "November",
        "December",
    ];

    let sorted = deepClone(month).sort();
    sorted.forEach((element, index) => {
        console.log("after Array.sort : " + index + ", " + element);
    })

    sorted = deepClone(month).reverse();
    sorted.forEach((element, index) => {
        console.log("after Array.reverse : " + index + ", " + element);
    })

    sorted = deepClone(month).sort((a, b) => {
        let secA = a.substring(1, 2);
        let secB = b.substring(1, 2);
        let diff = secA.localeCompare(secB); // 对于字符串来说，如果 secA 全等 secB 返回0，如果 secA 字母序 小于 secB, 返回 -1， 否则返回 1
        console.log("sort func, secA=" + secA + ", secB=" + secB + ", diff=" + diff);
        return diff; // 返回 -1 表示升序排序，a 排在 b 前面（a 比 b小）

        //return a.substring(1,2).localeCompare(b.substring(1, 2));
    })
    sorted.forEach((element, index) => {
        console.log("按第二个字母排序 : " + index + ", " + element);
    })

    month.forEach((element, index) => {
        console.log("原数组 : " + index + ", " + element);
    })
}

function demoLogic() {
    console.log("\narrayDemoLogic");
    arrayLoop();

    arraySort();
}

//module.exports.deepClone = deepClone;
//module.exports.demoLogic = demoLogic;

export{demoLogic, deepClone};